package com.mtwp.dfs.service.category;

import com.mtwp.dfs.domain.category.DiskStore;
import com.mtwp.dfs.repository.DiskStoreRepository;
import com.mtwp.dfs.service.category.stateprocess.DFSFuncMap;
import com.mtwp.dfs.service.dfs.FastDFSService;
import com.twp.common.component.process.statemachine.annotation.IMapFunctionListenerProcess;
import com.twp.common.component.process.statemachine.base.DefaultStateNodeComponent;
import com.twp.common.component.process.statemachine.domain.StateNode;
import com.twp.common.component.process.statemachine.domain.iinterface.IMapRouterProcessStateNodeFunc;
import com.twp.common.component.process.statemachine.translate.ITranslateState;
import com.twp.common.tuple.RequestDto;
import com.twp.common.tuple.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.javatuples.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class DiskStoreService {

    final String nextLevelPathCode = "______";

    @Autowired
    FastDFSService fastDFSService;

    @Autowired
    DiskStoreRepository diskStoreRepository;

    @Autowired
    DFSFuncMap dfsFuncMap;

    @Autowired
    ITranslateState<StateNode,Map,Map<StateNode,IMapRouterProcessStateNodeFunc<StateNode>>,ResultDTO,Exception> iTranslateState;

    @Autowired
    IMapFunctionListenerProcess<StateNode,Map<StateNode,IMapRouterProcessStateNodeFunc<StateNode>>> iMapFunctionListenerProcess;

    /*
    条件查询
     */
    public List<DiskStore> findByOption(DiskStore diskStore){
        return diskStoreRepository.findAll(
                (root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if (!StringUtils.isEmpty(diskStore.getName())){
                        predicates.add(criteriaBuilder.like(root.get("name"),  new StringBuffer("%").append(diskStore.getName()).append("%").toString()));
                    }
                    if (!StringUtils.isEmpty(diskStore.getLevel())){
                        predicates.add(criteriaBuilder.equal(
                                root.get("level"),diskStore.getLevel())
                        );
                    }
                    if (!StringUtils.isEmpty(diskStore.getPathCode())){
                        predicates.add(criteriaBuilder.like(
                                root.get("pathCode"),new StringBuffer(diskStore.getPath()).append(nextLevelPathCode).toString()
                        ));
                    }
                    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
        );
    }

    public void saveOrUpdate(DiskStore diskStore){
        diskStoreRepository.save(diskStore);
    }

    /*
    此处逻辑交错，所以使用状态机
     */
    public ResultDTO action(Principal principal,DiskStore diskStore){
        /*
        先获取路径，
        判断是否可存储或更新，判断是否锁定状态，或者已存在或其他
        决定更新具体
        执行中心fastdfs操作，
        成功后执行数据入库
         */
        ResultDTO<DiskStore> resultDTO = new DefaultStateNodeComponent(dfsFuncMap){
            @Override
            public StateNode onCreate() {
                return StateNode
                        .builder()
                        .nodeCode("dfs_action_requestEnter")
                        .requestDto(new RequestDto(){{
                            setPrincipal(principal);
                            setData(diskStore);
                        }})
                        .build();
            }

            @Override
            public Pair<Map, StateNode> onStart() {
                return Pair.with(new HashMap(),new StateNode().setNodeCode("dfs_action_end"));
            }

            @Override
            public void onException(Exception e) {
                log.error("dfs处理异常:",e.getMessage());
            }

            @Override
            public void onDestroy() {

            }
        }.setIMapFunctionListenerProcess(iMapFunctionListenerProcess).setITranslateState(iTranslateState).runOnResp();
        log.info(resultDTO.toString());
       // return resultDTO.getData();
        if (!resultDTO.getIsSuccess()){
            resultDTO.setMessage("上传失败");
        }
        return resultDTO;
    }
    /*
    logic删除
     */
    public void logicDelete(List<Integer> ids){
        diskStoreRepository.updateDiskStoreStatus(ids);
    }

    /*
    清空回收站
     */
    public void clear(List<Integer> ids){
        /*
        判断是否存储记录
        判断是否存在此存储节点
        判断当前状态是否可删除
        删除后进行表库删除
         */
        //得到已经存在的节点，并且非锁定的节点,即正常状态的节点
        List<DiskStore> diskStores = diskStoreRepository.findAllByIdInAndStatusInAndDownloadUrlNotNull(ids, Arrays.asList(1));

        List<String> fileUrlList =
                diskStores.stream()
                         .map(diskStore -> diskStore.getDownloadUrl())
                         .filter(url->!StringUtils.isEmpty(url))
                .collect(Collectors.toList());

        fastDFSService.deleteInFileList(fileUrlList);
        diskStoreRepository.delete(diskStores);

    }



}
